<?php
namespace Admin\Model;
use Think\Model;

class StyleModel extends Model{
	//自动验证
	protected $_validate = array(
		array('bgcolor','1,20','背景颜色不得为空或大于20位！',self::EXISTS_VALIDATE,'length'),
		array('bordercolor','1,20','边框颜色不得为空或大于20位！',self::EXISTS_VALIDATE,'length'),
		array('buttoncolor','1,20','按钮颜色不得为空或大于20位！',self::EXISTS_VALIDATE,'length'),
	);
	
	//查询总记录
	public function total(){
		return $this->where($this->map())->count();
	}
	
	//查询所有
	public function all($firstRow){
		return $this->field('id,bgcolor,bordercolor,buttoncolor,date')
    				->where($this->map())
    				->order(array('date'=>'DESC','id'=>'DESC'))
    				->limit($firstRow,C('PAGE_SIZE'))
    				->select();
	}
	
	//查询所有（不分页）
	public function all2(){
		return $this->field('id')
    				->order(array('id'=>'ASC'))
    				->select();
	}
	
	//查询一条
	public function one($id=0){
		$map['id'] = $id ? $id : I('get.id');
		return $this->field('bgcolor,bordercolor,buttoncolor')->where($map)->find();
	}
	
	//添加
	public function insert(){
		$data = array(
			'bgcolor'=>I('post.bgcolor'),
			'bordercolor'=>I('post.bordercolor'),
			'buttoncolor'=>I('post.buttoncolor'),
			'date'=>NOW_TIME
		);
		if ($this->create($data)){
			$id = $this->add();
			return $id ? $id : 0;
		}else{
			return $this->getError();
		}
	}
	
	//修改
	public function update(){
		$data = array(
			'id'=>I('get.id'),
			'bgcolor'=>I('post.bgcolor'),
			'bordercolor'=>I('post.bordercolor'),
			'buttoncolor'=>I('post.buttoncolor')
		);
		if ($this->create($data)){
			$id = $this->save();
			return $id ? $id : 0;
		}else{
			return $this->getError();
		}
	}
	
	//删除
	public function remove(){
		$affected_rows = $this->delete(I('get.id'));
		if ($affected_rows) $this->execute('OPTIMIZE TABLE `__PREFIX__style`');
		return $affected_rows;
	}
	
	//搜索
	private function map(){
		$map = array(
			'_complex'=>array(
				'bgcolor'=>array('like','%'.I('get.keyword').'%'),
				'bordercolor'=>array('like','%'.I('get.keyword').'%'),
				'buttoncolor'=>array('like','%'.I('get.keyword').'%'),
				'_logic'=>'OR'
			)
		);
		return $map;
	}
}